var CsObjct = null;
var CS = function() {};
CS.App = function(options) {
	var _this = this;
	CsObjct = _this;
	this.options = options;
	_this.viewer = new Cesium.Viewer(_this.options.domElement, {
		animation: true, //是否创建动画小器件，左下角仪表
		baseLayerPicker: true, //是否显示图层选择器
		fullscreenButton: true, //是否显示全屏按钮
		geocoder: true, //是否显示geocoder小器件，右上角查询按钮
		homeButton: true, //是否显示Home按钮
		infoBox: true, //是否显示信息框
		sceneModePicker: true, //是否显示3D/2D选择器
		selectionIndicator: true, //是否显示选取指示器组件
		timeline: true, //是否显示时间轴
		navigationHelpButton: true, //是否显示右上角的帮助按钮
		scene3DOnly: true, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
		clock: new Cesium.Clock(), //用于控制当前时间的时钟对象
		fullscreenElement: document.body, //全屏时渲染的HTML元素,
		useDefaultRenderLoop: true, //如果需要控制渲染循环，则设为true
		targetFrameRate: undefined, //使用默认render loop时的帧率
		showRenderLoopErrors: false, //如果设为true，将在一个HTML面板中显示错误信息
		automaticallyTrackDataSourceClocks: true, //自动追踪最近添加的数据源的时钟设置
		contextOptions: undefined, //传递给Scene对象的上下文参数（scene.options）
		sceneMode: Cesium.SceneMode.SCENE3D, //初始场景模式
		mapProjection: new Cesium.WebMercatorProjection(), //地图投影体系
		dataSources: new Cesium.DataSourceCollection()
	});
	
	//移动设备上禁掉以下几个选项，可以相对更加流畅
	if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
		viewer.scene.fog.enable = false;
		viewer.scene.skyAtmosphere.show = false;
		viewer.scene.fxaa = false;
	}
	_this.container = document.getElementById(_this.options.domElement);
	_this.viewer.scene.globe.depthTestAgainstTerrain = false;
	_this.viewer.scene.logarithmicDepthBuffer = true; //why

	// _this.viewer.scene.debugShowFramesPerSecond = true;

	_this.scene = _this.viewer.scene;
	_this.canvas = _this.viewer.canvas;
	_this.clock = _this.viewer.clock;
	_this.camera = _this.viewer.scene.camera;
	_this.entities = _this.viewer.entities;
	_this.primitives = _this.viewer.primitives;
	_this.handler = new Cesium.ScreenSpaceEventHandler(_this.scene.canvas);

	_this.flyToByPosition([102.932521, 25.100552, 1000], 3, function(e) {
		_this.load3dModel();
	});
	_this.translate();

	//键盘事件ctrl+shift+D切换模板操作
	document.addEventListener('keydown', function(event) {
		var e = event || window.event || arguments.callee.caller.arguments[0];
		if (e) {
			var keyCode = event.keyCode || event.which || e.charCode;
			if (event.ctrlKey == true && keyCode == 70) {
				_this.scene.debugShowFramesPerSecond = !_this.scene.debugShowFramesPerSecond;
				event.preventDefault();
			}
		}
	});

	var activeShapePoints = [];
	//三维坐标，获取模型表面的经纬度高程坐标
	_this.handler.setInputAction(function(evt) {
		var scene = _this.viewer.scene;
		//2D模式。使用正交投影从上至下查看地图。
		if (scene.mode == Cesium.SceneMode.SCENE2D) {
			console.log("2D模式。使用正交投影从上至下查看地图。");
		}
		//3D模式。地球的一个传统3D透视图。
		else if (scene.mode == Cesium.SceneMode.SCENE3D) {
			var pickedObject = scene.pick(evt.position);
			//三维坐标，获取模型表面的经纬度高程坐标
			if (scene.pickPositionSupported && Cesium.defined(pickedObject) && pickedObject.node) {
				if (Cesium.defined(pickedObject)) {
					console.log(pickedObject);
				}
				var cartesian = scene.pickPosition(evt.position);
				if (Cesium.defined(cartesian)) {
					var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
					var lng = Cesium.Math.toDegrees(cartographic.longitude);
					var lat = Cesium.Math.toDegrees(cartographic.latitude);
					var height = cartographic.height; //模型高度
					mapPosition = {
						x: lng,
						y: lat,
						z: height
					};
				}

			} else {
				//三维坐标，获取地形表面的经纬度高程坐标：
				var ray = _this.camera.getPickRay(evt.position);
				var cartesian = _this.scene.globe.pick(ray, _this.scene);
				var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
				var lng = Cesium.Math.toDegrees(cartographic.longitude); //经度值
				var lat = Cesium.Math.toDegrees(cartographic.latitude); //纬度值
				//height结果与cartographic.height相差无几，注意：cartographic.height可以为0，也就是说，可以根据经纬度计算出高程。
				var height = _this.scene.globe.getHeight(cartographic);
				var mapPosition = {
					x: lng,
					y: lat,
					z: height.height
				}; //height的值为地形高度
				console.log(mapPosition);
			}
		}
		//在各种模式（例如3D到2D）之间变形。
		else if (scene.mode == Cesium.SceneMode.MORPHING) {
			console.log("在各种模式（例如3D到2D）之间变形。");
		}
		//哥伦布查看模式。放置地图的2.5D透视图平面和高度非零的对象绘制在其上方。
		else if (scene.mode == Cesium.SceneMode.COLUMBUS_VIEW) {
			console.log("哥伦布查看模式。放置地图的2.5D透视图平面和高度非零的对象绘制在其上方");
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

	//鼠标移动
	_this.handler.setInputAction(function(event) {
		try {
			var cartesian = _this.viewer.camera.pickEllipsoid(event.position, _this.viewer.scene.globe.ellipsoid);
			if (Cesium.defined(cartesian)) {
				var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
				var lng = Cesium.Math.toDegrees(cartographic.longitude); //经度值
				var lat = Cesium.Math.toDegrees(cartographic.latitude); //纬度值
				var mapPosition = {
					x: lng,
					y: lat,
					z: cartographic.height
				};
			}
		} catch (e) {}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);


	_this.handler.setInputAction(function(event) {}, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

	_this.handler.setInputAction(function(wheelment) {
		console.log(wheelment);
	}, Cesium.ScreenSpaceEventType.WHEEL);

	_this.viewer.scene.camera.moveEnd.addEventListener(function() {})
	//handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
	//	new CS.App.video().Video2D();
	return _this;
}

/**
 * 飞到指定位置
 * @param {Object} position 位置
 * @param {Object} duration 持續動畫
 * @param {Object} callback 回調函數
 */
CS.App.prototype.flyToByPosition = function(position, duration, callback) {
	var _this = CsObjct;
	_this.camera.flyTo({
		destination: Cesium.Cartesian3.fromDegrees(position[0] * 1, position[1] * 1, position[2] * 1),
		orientation: {
			heading: Cesium.Math.toRadians(-15),
			pitch: Cesium.Math.toRadians(-65),
			roll: Cesium.Math.toRadians(0)
		},
		duration: duration ? duration : 0,
		complete: function() {
			if (callback) callback(_this);
		}
	});
}


//汉化帮助按钮
CS.App.prototype.translate = function() {
	var _this = CsObjct;
	var viewer = _this.viewer;
	if (viewer.navigationHelpButton) {
		viewer.navigationHelpButton.viewModel.tooltip = "操作指南";

		var clickHelper = viewer.navigationHelpButton.container.getElementsByClassName("cesium-click-navigation-help")[0];
		var touchHelper = viewer.navigationHelpButton.container.getElementsByClassName("cesium-touch-navigation-help")[0];

		var button = viewer.navigationHelpButton.container.getElementsByClassName("cesium-navigation-button-right")[0]
		button.innerHTML = button.innerHTML.replace(">Touch", ">手势");
		button = viewer.navigationHelpButton.container.getElementsByClassName("cesium-navigation-button-left")[0]
		button.innerHTML = button.innerHTML.replace(">Mouse", ">鼠标");

		var click_help_pan = clickHelper.getElementsByClassName("cesium-navigation-help-pan")[0];
		click_help_pan.innerHTML = "平移";
		var click_help_pan_details = click_help_pan.parentNode.getElementsByClassName("cesium-navigation-help-details")[0];
		click_help_pan_details.innerHTML = "按下左键 + 拖动";

		var click_help_zoom = clickHelper.getElementsByClassName("cesium-navigation-help-zoom")[0];
		click_help_zoom.innerHTML = "旋转";
		click_help_zoom.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "按下右键+拖动";
		click_help_zoom.parentNode.getElementsByClassName("cesium-navigation-help-details")[1].innerHTML = "";

		var click_help_rotate = clickHelper.getElementsByClassName("cesium-navigation-help-rotate")[0];
		click_help_rotate.innerHTML = "缩放";
		click_help_rotate.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "滚动鼠标滚轮";
		click_help_rotate.parentNode.getElementsByClassName("cesium-navigation-help-details")[1].innerHTML = "";

		//触屏操作
		var touch_help_pan = touchHelper.getElementsByClassName("cesium-navigation-help-pan")[0];
		touch_help_pan.innerHTML = "平移";
		touch_help_pan.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "单指拖动";

		var touch_help_zoom = touchHelper.getElementsByClassName("cesium-navigation-help-zoom")[0];
		touch_help_zoom.innerHTML = "缩放";
		touch_help_zoom.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "双指捏合";

		var touch_help_tilt = touchHelper.getElementsByClassName("cesium-navigation-help-rotate")[0];
		touch_help_tilt.innerHTML = "俯仰";
		touch_help_tilt.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "双指同向拖动";

		var touch_help_rotate = touchHelper.getElementsByClassName("cesium-navigation-help-tilt")[0];
		touch_help_rotate.innerHTML = "旋转";
		touch_help_rotate.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "双指反向拖动";
	}
}

/**
 * 生成uuid
 */
CS.App.prototype.uuid = function() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";
	var uuid = s.join("");
	return uuid;
}
/******************************************************************************************************************/
/**
 * 加载模型 http://127.0.0.1:8848/Z3DPro/assets/js/3d/ModelData/airport/road4.gltf
 */
CS.App.prototype.load3dModel = function(option) {
	var _this = CsObjct;

	var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
		Cesium.Cartesian3.fromDegrees(102.932521, 25.100552,
			0.0));

	// var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
	// 	Cesium.Cartesian3.fromDegrees(option.lng, option.lat,
	// 		option.height));	
	var model = _this.scene.primitives.add(Cesium.Model.fromGltf({
		url: 'http://127.0.0.1:8848/Z3DPro/assets/js/3d/ModelData/airport/road4.gltf',
		modelMatrix: modelMatrix,
		name: '飞机',
		id: _this.uuid(),
		minimumPixelSize: 1,
		maximumScale: 100,
		scale: 1.0
	}));
	var m = model.modelMatrix;
	var translation = Cesium.Cartesian3.fromArray([-520, -60, 0]);
	Cesium.Matrix4.multiplyByTranslation(m, translation, m);
	model.modelMatrix = m;
	var m1 = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(0));
	model.modelMatrix = Cesium.Matrix4.multiplyByMatrix3(m, m1, new Cesium.Matrix4());

	var m1 = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(0));
	model.modelMatrix = Cesium.Matrix4.multiplyByMatrix3(m, m1, new Cesium.Matrix4());
	var m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45 + 187.5));
	model.modelMatrix = Cesium.Matrix4.multiplyByMatrix3(m, m1, new Cesium.Matrix4());
	return model;
}
















/**
 * 创建点位
 * @param {Object} position 世界坐标
 */
CS.App.prototype.createPoint = function(worldPosition) {
	var _this = CsObjct;
	var point = _this.viewer.entities.add({
		id: _this.uuid(),
		position: worldPosition,
		point: {
			color: Cesium.Color.WHITE,
			pixelSize: 8
		}
	});
	//	_this.viewer.trackedEntity = point;
	//_this.viewer.zoomTo(point);    //居中到该点
	return point;
}

/**
 * 线
 * @param {Object} positions
 */
CS.App.prototype.drawLine = function(positions) {
	var _this = CsObjct;
	var shape = _this.viewer.entities.add({
		polyline: {
			positions: positions,
			clampToGround: true,
			width: 3
		}
	});
	return shape;
}

/**
 * 多边形
 * @param {Object} positions
 */
CS.App.prototype.drawPolygon = function(positions) {
	var _this = CsObjct;
	_this.viewer.entities.add({
		polygon: {
			hierarchy: positions,
			material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7))
		}
	});
}


CS.App.prototype.drawRectangle = function(positions) {
	var _this = CsObjct;
	var e = _this.viewer.entities.add({
		rectangle: {
			coordinates: Cesium.Rectangle.fromDegrees(-122.3, 46.0, -122.0, 46.3),
			material: Cesium.Color.RED.withAlpha(0.5)
		}
	});

}




/**
 * 视频投放
 * @param {Object} positions
 */
CS.App.prototype.add2DVideo = function(positions) {
	var _this = CsObjct;
	var videoElement = document.getElementById('trailer');
	_this.viewer.entities.add({
		polygon: {
			hierarchy: positions,
			material: videoElement,
			stRotation: Cesium.Math.toRadians(0),
			perPositionHeight: !0,
			outline: !1
		}
	});
}




CS.App.prototype.add3DVideo = function(positions) {
	var _this = CsObjct;
	var videoElement = document.getElementById('trailer');
	var e = _this.viewer.entities.add({
		polygon: {
			hierarchy: positions,
			material: videoElement,
			classificationType: Cesium.ClassificationType.BOTH,
		}
	});
}




//var radar = viewer.entities.getById('radar')；
//viewer.entities.remove(radarEntity);
//viewer.entities.removeAll();

CS.App.video = function() {}
CS.App.video.prototype.Video2D = function() {
	var _this = CsObjct;
	var videoElement = document.getElementById('trailer');
	this.cameraPosition = Cesium.Cartesian3.fromDegrees(102.92846, 25.096386, 100);
	this.tagPosition = Cesium.Cartesian3.fromDegrees(102.93512272580098, 25.098861131092804, 0);
	new Cesium.VideoShed3D(_this.viewer, {
		type: 3,
		url: "http://127.0.0.1:8848/Z3DPro/assets/js/3d/ModelData/airport/1.mp4",
		cameraPosition: this.cameraPosition,
		position: this.tagPosition,
		alpha: 1,
		debugFrustum: true
	});
}
